有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在忽略数字的同时移动字符串中的字符

我需要创建一个输入为字符串的方法,例如:asd321tre2。 输出应为:eas321dtr2。字符应向前移动一个位置,但数字应保持在同一位置。 输入:字符串s1=“abc23sd23”; 输出:String s2=“dab23cs23”

public static String revertTheString (String s) {
    String helper = s.replaceAll("\\d", "");
    helper = helper.substring(helper.length()-1) + helper.substring(0, helper.length()-1);
    int start = 0, end = 0;

    StringBuilder revert = new StringBuilder(s);

    for (int i = 0; i< s.length(); i++) {
        if(Character.isDigit(s.charAt(i))){
            end = i;
            revert = revert.replace(start, end, helper.substring(start, end));
            while(Character.isDigit(s.charAt(i))){
                i++;
                start = i;
            }
        }
    }
    return revert.toString();
}

共 (1) 个答案

  1. # 1 楼答案

    您可以尝试交换第一个和最后一个字符值,如下所示

    ====================================================================================

        String s = "asd321tre2";
        char[] charr = s.toCharArray();
        int end = 0;
    
        for (int i = s.length(); i <= 0; i ) {
            if (Character.isLetter(charr[i])) {
                end = i;
    
            }
        }
        String output = charReplace(end, charr);
    }
    
    private static String charReplace(int end, char[] ch) {
    
        for (int i = 0; i < ch.length; i++) {
            if (Character.isLetter(ch[i])) {
                char tmp = ch[i];
                ch[i] = ch[end];
                ch[end] = tmp;
            }
        }
        String output = String.valueOf(ch);
        return output;
    
    }
    

    ====================================================================================

    希望这有帮助

    谢谢, 帕提班